package com.zjeav.lingjiao.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.maning.mndialoglibrary.MProgressDialog;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.comon.CommonPersenter;
import com.zjeav.lingjiao.base.comon.CommonView;
import com.zjeav.lingjiao.base.config.BaseConfig;
import com.zjeav.lingjiao.base.request.OtherLoginRequest;
import com.zjeav.lingjiao.base.response.AccessToken;
import com.zjeav.lingjiao.base.response.VersionResponse;
import com.zjeav.lingjiao.base.response.WXName;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.ui.home.RestructureMainActivity;
import com.zjeav.lingjiao.ui.login.LoginContract;
import com.zjeav.lingjiao.ui.login.UserPresenter;
import com.zjeav.lingjiao.ui.personCenter.SysSetActivity;
import com.zjeav.lingjiao.ui.personCenter.view.SysContract;
import com.zjeav.lingjiao.ui.presenter.SysPresenter;

import okhttp3.ResponseBody;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler, CommonView.View, LoginContract.View ,SysContract.View{

    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;


    private CommonPersenter persenter;
    private UserPresenter userPresenter;
    private SysPresenter sysPresenter;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, "wxd7c954bd04cef4dc", false);
        persenter = new CommonPersenter(this);
        userPresenter = new UserPresenter(this);
        sysPresenter=new SysPresenter(this);
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
//				goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//				goToShowMsg((ShowMessageFromWX.Req) req);
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

//        Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = R.string.errcode_success;
                String code = ((SendAuth.Resp) resp).code;
                MProgressDialog.showProgress(this, "微信授权信息获取...");
                persenter.getAccessToken(BaseConfig.APP_ID, BaseConfig.AppSecret, code, BaseConfig.grant_type);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.errcode_deny;
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                result = R.string.errcode_unsupported;
                break;
            default:
                result = R.string.errcode_unknown;
                break;
        }

//        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }


    @Override
    public void getLoadResult(ResponseBody body, int type) {

    }

    @Override
    public void getAccessToken(AccessToken token) {
        MProgressDialog.showProgress(this, "登录中...");
        OtherLoginRequest otherLoginRequest = new OtherLoginRequest(token.getAccess_token(), token.getOpenid());
        int type= (int) SharedPreferencesUtils.getParam(this,"weChat",0);
        if (type==0){
            userPresenter.weiXinLogin(otherLoginRequest);
        }else {
            sysPresenter.bindWechat(otherLoginRequest);
        }

    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void skipActivity() {
        SharedPreferencesUtils.setParam(this, "wechatlogin", "0");
        Intent intent=new Intent(this, RestructureMainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void dissDiagle() {
        MProgressDialog.dismissProgress();
    }

    @Override
    public void getVersion(VersionResponse versionResponse) {

    }

    @Override
    public void bindWeChat(WXName response) {
        MProgressDialog.dismissProgress();
        Intent intent=new Intent(this, SysSetActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void showError(Throwable throwable, String message) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, ErrorUtils.showError(throwable,message),Toast.LENGTH_SHORT).show();
        Intent intent=new Intent(this, SysSetActivity.class);
        startActivity(intent);
        finish();
    }
}